// Package service 处理业务逻辑
package service

import (
	"errors"
	"gforum/global"
	"gforum/model"
	"time"

	"gorm.io/gorm"
)

func AddCheckInExp(username string) (model.UserLevel, error) {

	var user model.User
	err := global.Db.Where("username = ?", username).First(&user).Error
	if err != nil {
		return model.UserLevel{}, ErrRecordNotFound
	}

	var checkIn model.CheckIn

	today := time.Now().Truncate(24 * time.Hour)

	// 限制用户一天仅进行一次签到，同时区分查询异常和用户当日未签到的情况
	var check model.CheckIn
	err = global.Db.Where("user_id = ? AND date = ?", user.ID, today).First(&check).Error

	if err == nil {
		return model.UserLevel{}, ErrAlreadyCheckedIn
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return model.UserLevel{}, err
	}

	checkIn = model.CheckIn{
		UserID: user.ID,
		Date:   today,
	}
	if err := global.Db.Create(&checkIn).Error; err != nil {
		return model.UserLevel{}, err
	}

	userlevel := user.CheckIn()

	if err = global.Db.Save(&user).Error; err != nil {
		return model.UserLevel{}, err
	}

	return userlevel, nil
}
